import React, { useState } from 'react';

import { useControllableValue } from 'ahooks';
import { message } from 'antd';
import cs from 'classnames';
import type { Editor as TinyMCEEditor } from 'tinymce';

import { filePlusUpload } from '@/services/base/kuozhangongnengwenjianguanliPlus';
import { parseSrc } from '@/utils';
import { Editor, IAllProps } from '@tinymce/tinymce-react';

import styles from './index.module.scss';

export type TinymcProps = IAllProps & {};

const Tinymc: React.FC<TinymcProps> = ({ init: initProps, ...rest }) => {
  const [instance, setInstance] = useState<TinyMCEEditor>();
  const [value, setValue] = useControllableValue(rest, {
    defaultValue: ''
  });

  const onEditorChange: TinymcProps['onEditorChange'] = (e) => {
    setValue(e);
  };
  const onInit: TinymcProps['onInit'] = (evt, editor) => {
    setInstance(editor);
  };

  const images_upload_handler: NonNullable<TinymcProps['init']>['images_upload_handler'] = (
    blobInfo
  ) => {
    const formData = new FormData();
    formData.append('file', blobInfo.blob());
    formData.append('name', blobInfo.filename());
    formData.append('filePurpose', '1');
    formData.append('showState', '1');

    // message.loading({ content: `${file.name}上传中...`, key: file.name });

    return filePlusUpload(
      {} as ArgumentsType<typeof filePlusUpload>[0],
      {},
      {} as ArgumentsType<typeof filePlusUpload>[2],
      {
        method: 'POST',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        tupleResponse: false,
        timeout: 60000,
        skipErrorHandler: true
      }
    ).then((res) => {
      if (res.data && res.data.url) {
        return parseSrc(res.data.url) as string;
      }

      return Promise.reject(res.message || '上传失败！');
    });
  };

  const file_picker_callback: NonNullable<TinymcProps['init']>['file_picker_callback'] = (
    callback,
    value,
    meta
  ) => {
    const ipt = document.createElement('input');
    ipt.setAttribute('type', 'file');

    if (meta.filetype === 'image') {
      ipt.setAttribute(
        'accept',
        'image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp'
      );
    } else if (meta.filetype === 'media') {
      ipt.setAttribute('accept', 'video/*, audio/*');
    }

    ipt.onchange = (e) => {
      const [file] = Array.from((e.target as HTMLInputElement).files || []);

      if (!file) {
        return;
      }

      const formData = new FormData();
      formData.append('file', file);
      formData.append('name', file.name);
      formData.append('filePurpose', '1');
      formData.append('showState', '1');

      message.loading({
        content: `${file.name}上传中...`,
        key: file.name
      });

      filePlusUpload(
        {} as ArgumentsType<typeof filePlusUpload>[0],
        {},
        {} as ArgumentsType<typeof filePlusUpload>[2],
        {
          tupleResponse: false,
          method: 'POST',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          data: formData,
          timeout: 60000,
          skipErrorHandler: true
        }
      )
        .then((res) => {
          if (res.data && res.data.url) {
            const src = parseSrc(res.data.url) as string;

            if (meta.filetype === 'file') {
              callback(src, { text: file.name });
            } else if (meta.filetype === 'image') {
              callback(src, { alt: file.name });
            } else if (meta.filetype === 'media') {
              callback(src, {});
            }
          } else {
            message.error(res.message || '上传失败！');
          }
        })
        .finally(() => {
          message.destroy(file.name);
          ipt.remove();
        });
    };

    ipt.click();
  };

  return (
    <div
      className={cs(styles['editor'], {
        [styles['load']]: instance
      })}
    >
      <Editor
        tinymceScriptSrc={`${import.meta.env.BASE_URL}lib/tinymce/tinymce.min.js`}
        onInit={onInit}
        init={{
          language: 'zh_CN',
          height: 500, //编辑器高度
          min_height: 300,
          // 去除logo
          branding: false,
          // 除去升级logo
          promotion: false,
          upgrade: false,
          paste_data_images: true,
          file_picker_types: 'file image media',
          // 自定义图片上传
          images_upload_handler,
          // 自定义文件上传
          file_picker_callback,
          powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
          powerpaste_html_import: 'propmt', // propmt, merge, clear
          powerpaste_allow_local_images: true,
          // end 自定义文件上传
          plugins: [
            'powerpaste',
            'advlist',
            'autolink',
            'lists',
            'link',
            'image',
            'charmap',
            'anchor',
            'searchreplace',
            'visualblocks',
            'code',
            'fullscreen',
            'insertdatetime',
            'media',
            'table',
            'preview',
            'help',
            'wordcount'
          ],
          toolbar: [
            `fullscreen | preview | undo redo | blocks | bold italic forecolor | alignleft aligncenter alignright | removeformat`,
            `image | link | media | alignright alignjustify | bullist numlist outdent indent`
          ],
          content_style: `
            body { font-family:Helvetica,Arial,sans-serif; font-size:14px };
            img {max-width:100%;}
          `,
          ...initProps
        }}
        {...rest}
        onChange={undefined}
        value={value}
        onEditorChange={onEditorChange}
      />
    </div>
  );
};

export default Tinymc;
